import request from "request-promise";
import { writeFileAsync, readFileAsync } from "./utils";
import { resolve } from "path";

const r = path => resolve(__dirname,"../database/backup/", path);
const reqApi = "http://api.shenjian.io/?appid=307067dd799ae392c14ef065e1cfc293";

class Imdb {
  constructor() {
    this.backUpFilePath = "./backup";
    this.reqApi = reqApi;
  }

  // 备份
  async backUp() {
    const res = await request(this.reqApi);
    const getRes = JSON.parse(res);
    let result;
    if (getRes.error_code === 0) {
      result = await writeFileAsync(
        r("Imdb.json"),
        JSON.stringify(getRes.data)
      );
    }
    return result;
  }

  // 替换
  async replaceData() {
    const Imdb = await readFileAsync(r("Imdb.json"));
    const wikiCharacters = await readFileAsync(r("wikiCharacters.json"));

    const resImdb = JSON.parse(Imdb);
    const resCharacters = JSON.parse(wikiCharacters);
    let resArr = [];
    resImdb.forEach( n => {
      resCharacters.forEach(m => {
        if(m.nmId === n.nmId){
          m.images = n.images;
          m.profile = n.profile;
        };
        // delete m._id;
      })
    })
    const save = await writeFileAsync(r("characters.json"),JSON.stringify(resCharacters,null,2))

    return save;
  }
}

export default new Imdb();
